import { usePermissionStore } from "@/store";
import router from "@/router";
// 白名单路由
const whiteList = ["/login", "/404", "/401"];

export function setupPermission() {
  const permissionStore = usePermissionStore();
  router.beforeEach(async (to, from, next) => {
    // next();
    if (import.meta.env.VITE_NEED_TOKEN == "true") {
      const token = localStorage.getItem("token");
      if (!token && !whiteList.includes(to.path)) {
        next({ path: "/login" });
      } else {
        if (to.path === "/login") {
          next();
        } else if (permissionStore.routesLoaded) {
          console.log(666);

          if (to.matched.length === 0) {
            // next({ path: "/login" });
            next({ path: "/" });
          } else {
            next();
          }
        } else {
          try {
            // 生成动态路由
            const dynamicRoutes = await permissionStore.getRoutesRequest();
            console.log(66677);
            next({ ...to, replace: true });

            next();
          } catch (error) {
            next({ path: "/login" });
          }
        }
      }
    } else {
      next();
    }
    // next()
  });
}
